import os

from django.conf import settings
from rest_framework import serializers

from apps.club_system.club.models import ClubCancel
from apps.common.account.models import Account


class ClubCancelListSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    club = serializers.StringRelatedField()
    account = serializers.SlugRelatedField(label='申请人', slug_field='realname', read_only=True)
    club_id = serializers.IntegerField()
    account_id = serializers.IntegerField()

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        # 返回个人信息
        ret['realname'] = instance.account.realname if instance.account else None
        ret['username'] = instance.account.username if instance.account else None
        ret['student_community'] = instance.account.student_community if instance.account else None
        ret['politics_status'] = instance.account.politics_status if instance.account else None
        ret['faculty_title'] = instance.account.faculty_title if instance.account else None
        # 添加审核历史
        ret['check_history'] = []
        check_qs = instance.club_cancel_check.order_by('-created_time').only(
            'account', 'check_opinion', 'check_status', 'check_level', 'created_time'
        )
        check_level_fomat = {1: '一级审核', 2: '二级审核'}
        for i in check_qs:
            tmp = {
                'account': i.account.realname,
                'check_opinion': i.check_opinion,
                'check_status': i.check_status,
                'check_level_name': check_level_fomat.get(i.check_level, '审核'),
                'created_time': i.created_time,
            }
            ret['check_history'].append(tmp)
        # 添加图片
        image = instance.image
        ret['image'] = []
        ret['image'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data', '')}",
            'name': obj.get('file_name', ''),
        } for obj in image]
        # 添加文件
        files_all = instance.file
        ret['files'] = []
        ret['files'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data', '')}",
            'name': obj.get('file_name', ''),
        } for obj in files_all]
        return ret

    class Meta:
        model = ClubCancel
        fields = (
            'id', 'club_id', 'club', 'account_id', 'account', 'updated_time', 'created_time', 'first_check_status',
            'second_check_status', 'record',)


class ClubCancelDetailSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    club = serializers.StringRelatedField(read_only=True)
    club_id = serializers.IntegerField()
    account = serializers.HiddenField(  # 默认为当前创建者
        default=serializers.CurrentUserDefault()
    )

    # #测试用
    # account_id = serializers.IntegerField()
    # account = serializers.StringRelatedField(read_only=True)

    def update(self, instance, validated_data):
        # 每次修改都将两个审核改为待审核
        validated_data['first_check_status'] = '待审核'
        validated_data['second_check_status'] = '待审核'
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        # account_info = Account.objects.filter(id=instance.account_id) \
        #     .values('realname', 'username', 'telephone', 'faculty_title', 'class_title', 'politics_status')
        # ret['account_info'] = account_info
        # 返回个人信息
        ret['realname'] = instance.account.realname if instance.account else None
        ret['username'] = instance.account.username if instance.account else None
        ret['student_community'] = instance.account.student_community if instance.account else None
        ret['politics_status'] = instance.account.politics_status if instance.account else None
        ret['faculty_title'] = instance.account.faculty_title if instance.account else None
        # 添加审核历史
        ret['check_history'] = []
        check_qs = instance.club_cancel_check.order_by('-created_time').only(
            'account', 'check_opinion', 'check_status', 'check_level', 'created_time'
        )
        check_level_fomat = {1: '一级审核', 2: '二级审核'}
        for i in check_qs:
            tmp = {
                'account': i.account.realname,
                'check_opinion': i.check_opinion,
                'check_status': i.check_status,
                'check_level_name': check_level_fomat.get(i.check_level, '审核'),
                'created_time': i.created_time,
            }
            ret['check_history'].append(tmp)

        ret['files'] = [{'url': f"{settings.IMAGE_URL}{file.get('data')}", 'name': file.get('file_name')}
                        for file in instance.file]
        ret['image'] = [{'url': f"{settings.IMAGE_URL}{file.get('data')}", 'name': file.get('file_name')}
                        for file in instance.image]
        return ret

    class Meta:
        model = ClubCancel
        fields = '__all__'


# 社团注销一级审核序列化器
class CancelFirstCheckSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    account_id = serializers.IntegerField(read_only=True)
    account = serializers.SlugRelatedField(label='申请人', slug_field='realname', read_only=True)
    club_id = serializers.IntegerField(read_only=True)
    club = serializers.StringRelatedField(read_only=True)

    def to_representation(self, instance):
        ret = super(CancelFirstCheckSerializer, self).to_representation(instance)
        # 返回个人信息
        ret['realname'] = instance.account.realname if instance.account else None
        ret['username'] = instance.account.username if instance.account else None
        ret['student_community'] = instance.account.student_community if instance.account else None
        ret['politics_status'] = instance.account.politics_status if instance.account else None
        ret['faculty_title'] = instance.account.faculty_title if instance.account else None
        # 添加图片
        image = instance.image
        ret['image'] = []
        ret['image'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data', '')}",
            'name': obj.get('file_name', ''),
        } for obj in image]
        # 添加文件
        files_all = instance.file
        ret['files'] = []
        ret['files'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data', '')}",
            'name': obj.get('file_name', ''),
        } for obj in files_all]
        return ret

    class Meta:
        model = ClubCancel
        fields = '__all__'


# 社团注销二级审核序列化器
class CancelSecondCheckSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    account_id = serializers.IntegerField(read_only=True)
    account = serializers.SlugRelatedField(label='申请人', slug_field='realname', read_only=True)
    club_id = serializers.IntegerField(read_only=True)
    club = serializers.StringRelatedField(read_only=True)

    def to_representation(self, instance):
        ret = super(CancelSecondCheckSerializer, self).to_representation(instance)
        # 返回个人信息
        ret['realname'] = instance.account.realname if instance.account else None
        ret['username'] = instance.account.username if instance.account else None
        ret['student_community'] = instance.account.student_community if instance.account else None
        ret['politics_status'] = instance.account.politics_status if instance.account else None
        ret['faculty_title'] = instance.account.faculty_title if instance.account else None
        # 添加图片
        image = instance.image
        ret['image'] = []
        ret['image'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data', '')}",
            'name': obj.get('file_name', ''),
        } for obj in image]
        # 添加文件
        files_all = instance.file
        ret['files'] = []
        ret['files'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data', '')}",
            'name': obj.get('file_name', ''),
        } for obj in files_all]
        # 添加一级审核的意见
        check_qs = instance.club_cancel_check.filter(check_level=1).order_by('-created_time').first()
        ret['first_check_opinion'] = check_qs.check_opinion if check_qs else ''
        return ret

    class Meta:
        model = ClubCancel
        fields = '__all__'


class CancelPassSerializer(serializers.ModelSerializer):
    account_id = serializers.IntegerField(read_only=True)
    account = serializers.SlugRelatedField(label='申请人', slug_field='realname', read_only=True)
    club_id = serializers.IntegerField(read_only=True)
    club = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = ClubCancel
        fields = ('id', 'account_id', 'account', 'club_id', 'club')
